<!-- src/components/qrcode/clientEntry.vue -->
<script setup>
import { ref, onMounted, watch, defineProps, defineExpose } from 'vue'
import QRCode from 'qrcode'

const props = defineProps({
    text: {
        type: String,
        required: true
    },
    visible: {
        type: Boolean,
        default: true
    }
})

const qrCodeCanvas = ref(null)

// 暴露刷新方法给父组件
defineExpose({
    refresh
})

// 正确暴露的refresh方法
async function refresh() {
    try {
        if (qrCodeCanvas.value && props.text) {
            // 清空画布
            const ctx = qrCodeCanvas.value.getContext('2d')
            ctx.clearRect(0, 0, qrCodeCanvas.value.width, qrCodeCanvas.value.height)

            // 重新生成二维码
            await QRCode.toCanvas(qrCodeCanvas.value, props.text, {
                width: 200,
                margin: 2
            })
        }
    } catch (error) {
        console.error('刷新二维码失败:', error)
    }
}


// 监听text变化
watch(() => props.text, (newVal) => {
    if (newVal) refresh()
})

onMounted(() => {
    if (props.visible) refresh()
})
</script>

<template>
    <canvas ref="qrCodeCanvas" class="qr-code" v-show="visible"></canvas>
</template>